"use strict"

/**
 * login/logout controller 
 * 
 */

var q = require("q");
var db = require("../db");
var dateFormat = require('dateformat');

var loginHandle = {
    doLogin: function (req, res) { // 登录验证
        var name = req.body.name || "admin";
        var password = req.body.password || "";
        var sql = "select * from user where name='" + name + "' and password='" + password + "'";
        console.log("sql->" + sql);

        var defer = q("");
        defer.then(function () {
            var d = q.defer();
            db.query(sql, function (err, recs) {
                if (err) {
                    d.resolve(0);
                } else {
                    var r = recs.length;
                    d.resolve(r);
                }
            });
            return d.promise;
        }).then(function (cnt) {
            if (cnt == 0) {
                res.render("login", { "warning": "用户名或者密码不正确" });
            } else {
                req.session.user_id = 1;
                res.redirect("/admin");
            }
        });
    },
    login: function (req, res) { // 登录界面
        if (req.session.user_id) { // 已经登录，进入管理员页面
            res.redirect("/admin");
            return;
        }
        res.render("login", {});
    },
    logout: function (req, res) { // 注销操作
        req.session.user_id = 0;
        res.redirect("/login");
    }
}

exports = module.exports = {
    "/login": loginHandle.login,
    "/logout": loginHandle.logout,
    "/doLogin": { post: loginHandle.doLogin }
};